"""交易服务模块"""
import datetime
import random
from app.database import get_db_connection

def generate_transaction_no():
    """生成唯一的交易流水号"""
    now = datetime.datetime.now()
    return now.strftime('%Y%m%d%H%M%S') + str(random.randint(1000, 9999))

def settle_bill(cart_items, operator='admin'):
    """结算账单"""
    connection = None
    cursor = None
    
    try:
        connection = get_db_connection()
        cursor = connection.cursor()
        connection.begin()
        
        total = 0
        product_details = []
        
        for item in cart_items:
            barcode = item.get('barcode')
            quantity = item.get('quantity', 1)
            
            cursor.execute(
                "SELECT price, stock, name FROM products WHERE barcode = %s",
                (barcode,)
            )
            product = cursor.fetchone()
            
            if product:
                if product['stock'] < quantity:
                    connection.rollback()
                    raise ValueError(f'商品 {barcode} 库存不足')
                
                subtotal = product['price'] * quantity
                total += subtotal
                
                product_details.append({
                    'barcode': barcode,
                    'name': product['name'],
                    'price': product['price'],
                    'quantity': quantity,
                    'subtotal': subtotal
                })
                
                cursor.execute(
                    "UPDATE products SET stock = stock - %s WHERE barcode = %s",
                    (quantity, barcode)
                )
            else:
                connection.rollback()
                raise ValueError(f'商品 {barcode} 不存在')
        
        transaction_no = generate_transaction_no()
        
        cursor.execute(
            "INSERT INTO transactions (transaction_no, total_amount, operator) VALUES (%s, %s, %s)",
            (transaction_no, total, operator)
        )
        transaction_id = cursor.lastrowid
        
        for detail in product_details:
            cursor.execute(
                "INSERT INTO transaction_details (transaction_id, barcode, product_name, price, quantity, subtotal) VALUES (%s, %s, %s, %s, %s, %s)",
                (transaction_id, detail['barcode'], detail['name'], detail['price'], detail['quantity'], detail['subtotal'])
            )
        
        connection.commit()
        return {'success': True, 'total': total, 'transaction_no': transaction_no}
    except Exception as e:
        if connection:
            connection.rollback()
        raise e
    finally:
        if cursor:
            cursor.close()
        if connection:
            connection.close()

def get_transactions(page=1, per_page=10, search_no=None):
    """获取交易记录列表"""
    connection = None
    cursor = None
    
    try:
        connection = get_db_connection()
        cursor = connection.cursor()
        
        offset = (page - 1) * per_page
        where_clause = ""
        params = []
        
        if search_no:
            where_clause = "WHERE transaction_no LIKE %s"
            params.append(f"%{search_no}%")
        
        cursor.execute(f"SELECT COUNT(*) as total FROM transactions {where_clause}", params)
        total_records = cursor.fetchone()['total']
        
        total_pages = (total_records + per_page - 1) // per_page
        
        sql = f"""
            SELECT id, transaction_no, transaction_time, total_amount
            FROM transactions 
            {where_clause}
            ORDER BY transaction_time DESC
            LIMIT %s OFFSET %s
        """
        
        params.extend([per_page, offset])
        cursor.execute(sql, params)
        transactions = cursor.fetchall()
        
        return {
            'transactions': transactions,
            'total_pages': total_pages,
            'current_page': page,
            'total_records': total_records
        }
    finally:
        if cursor:
            cursor.close()
        if connection:
            connection.close()

def get_transaction_details(transaction_id):
    """获取交易明细"""
    connection = None
    cursor = None
    
    try:
        connection = get_db_connection()
        cursor = connection.cursor()
        
        cursor.execute(
            "SELECT transaction_no, transaction_time, total_amount, operator FROM transactions WHERE id = %s",
            (transaction_id,)
        )
        transaction = cursor.fetchone()
        
        if not transaction:
            return None
        
        cursor.execute(
            "SELECT barcode, product_name, price, quantity, subtotal FROM transaction_details WHERE transaction_id = %s ORDER BY id",
            (transaction_id,)
        )
        details = cursor.fetchall()
        
        return {
            'transaction': transaction,
            'details': details
        }
    finally:
        if cursor:
            cursor.close()
        if connection:
            connection.close()

